import { Button, message, notification } from 'antd';
import defaultSettings from '../config/defaultSettings';

interface Params {
  left: number;
  top: number;
  currentX: number;
  currentY: number;
  flag: boolean;
}

const { pwa } = defaultSettings;
const isHttps = document.location.protocol === 'https:';
document.body.classList.add('lightTheme');

const clearCache = () => {
  if (window.caches) {
    caches
      .keys()
      .then((keys) => {
        keys.forEach((key) => {
          caches.delete(key);
        });
      })
      .catch((e) => console.log(e));
  }
};

// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning('密码找不到');
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });

      clearCache();
      window.location.reload();
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        app.pwa.serviceworker.updated.ok
      </Button>
    );
    notification.open({
      message: 'app.pwa.serviceworker.updated',
      description: 'app.pwa.serviceworker.updated.hint',
      btn,
      key,
      onClose: async () => null,
    });
  });
} else if ('serviceWorker' in navigator && isHttps) {
  // unregister service worker
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then((sws) => {
      sws.forEach((sw) => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then((sw) => {
    if (sw) sw.unregister();
  });
  clearCache();
}
const params: Params = {
  left: 0,
  top: 0,
  currentX: 0,
  currentY: 0,
  flag: false,
};
//获取相关CSS属性
const getCss = function (o: any, key: string) {
  return o.currentStyle ? o.currentStyle[key] : document.defaultView?.getComputedStyle(o)[key];
};

//拖拽的实现
const startDrag = function (
  bar: HTMLElement,
  target: HTMLElement,
  callback?: (param1: number, param2: number) => void,
) {
  if (getCss(target, 'left') !== 'auto') {
    params.left = getCss(target, 'left');
  }
  if (getCss(target, 'top') !== 'auto') {
    params.top = getCss(target, 'top');
  }
  //o是移动对象
  bar.onmousedown = function (event: any) {
    let newEvent = event;
    params.flag = true;
    if (!newEvent) {
      newEvent = window.event;
      //防止IE文字选中
      bar.onselectstart = function () {
        return false;
      };
    }
    params.currentX = newEvent.clientX;
    params.currentY = newEvent.clientY;
  };
  document.onmouseup = function () {
    params.flag = false;
    if (getCss(target, 'left') !== 'auto') {
      params.left = getCss(target, 'left');
    }
    if (getCss(target, 'top') !== 'auto') {
      params.top = getCss(target, 'top');
    }
  };
  document.onmousemove = function (event: any) {
    const e = event ? event : window.event;
    if (params.flag) {
      const nowX = e.clientX,
        nowY = e.clientY;
      const disX = nowX - params.currentX,
        disY = nowY - params.currentY;
      target.style.left = parseInt(params.left as unknown as string) + disX + 'px';
      target.style.top = parseInt(params.top as unknown as string) + disY + 'px';

      if (typeof callback == 'function') {
        callback(
          (parseInt(params.left as unknown as string) || 0) + disX,
          (parseInt(params.top as unknown as string) || 0) + disY,
        );
      }

      if (event.preventDefault) {
        event.preventDefault();
      }
      return false;
    }
  };
};
onload = function () {
  const bar = document.getElementById('waifu');
  const box = document.getElementById('waifu');
  if (bar && box) {
    startDrag(bar, box);
  }
};
